import React, { PureComponent } from "react";
import { Card, Divider, Popconfirm, Spin, Tag } from "antd";
import { connect } from "dva";
import { Link } from "react-router-dom";
import queryString from "query-string";
import Catalogue from "components/catalogue/Catalogue";
import dynamic from "umi/dynamic";
import styles from "./index.less";

import CardTitle from "./components/CardTitle";
import PageLayout from "../../../components/pageconlayout/PageLayout";
import TableList from "../../../components/tablelist/TableList";
import QueryExtra from "./components/QueryExtra";
// import AdvancedFilter from "./components/AdvancedFilter";
import CustomForm from "../../../components/customForm/CustomForm";

import { openNotificationWithIcon, delay } from "../../../utils/comm";
// import { detailFormat } from "../formbuilder/nomalFn";
import {
  getMenuRouter,
  getPageOperate,
} from "../../../components/layouts/menuFn";

const CreateForm = dynamic({
  loader: async () => {
    await delay(1000);
    return import("./components/CreateForm");
  },
});
const AdvancedFilter = dynamic({
  loader: async () => {
    await delay(1000);
    return import("./components/AdvancedFilter");
  },
});

const renderTag = (status) => {
  switch(status) {
    case 1:
      return <Tag color="#87d068">已发布</Tag>;
    case 2:
      return <Tag color="#e9e800">已停用</Tag>;
    default:
      return <Tag color="#999">未发布</Tag>;
  }
}

@connect(({ FormConfigure, appListMenu, loading, Public }) => ({
  formConfigStore: FormConfigure,
  loading,
  focusApp: appListMenu.focusApp,
  menuDataList: Public.menuDataList,
  resourceList: Public.resourceList,
  // tenantList: appListMenu.tenantList,
  appListMenuData: appListMenu.appListMenuData,
}))
class FormConfigure extends PureComponent {
  tenantId = undefined;

  appId = undefined;

  busiId = undefined;

  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon;
    this.getMenuRouter = getMenuRouter.bind(this);
    this.getPageOperate = getPageOperate.bind(this);
    this.state = {
      page: {
        pageNum: 1,
        pageSize: 6,
      },
      visible: false,
      filterVisible: false,
      formVisible: false,
      viewDatas: [],
      selectedKeys: [],
    };
    this.baseQueryParam = {
      searchName: "",
      searchKey: "",
      timeStart: "", // 开始时间
      timeEnd: "", // 结束时间
    };
    this.queryParams = this.baseQueryParam;
    this.columns = [
      {
        title: "表单名称",
        dataIndex: "formName",
        key: "formName",
        render: (text, item) => (
          <>
            {text}
            &nbsp;&nbsp;
            {renderTag(item.status)}
          </>
        ),
      },
      {
        title: '版本号',
        dataIndex: 'version',
        key: 'version',
        // width: '12%',
        hiddenTooltip: true,
      },
      {
        title: "表单编码",
        dataIndex: "formKey",
        key: "formKey",
        hiddenTooltip: true,
      },
      // {
      //   title: "修改时间",
      //   dataIndex: "updateTime",
      //   key: "updateTime",
      //   width: "20%",
      // },
      //  {
      //   title: '修改人',
      //   dataIndex: 'creatorName',
      //   key: 'creatorName',
      //   width: '16%',
      // },
      {
        title: "创建时间",
        dataIndex: "createTime",
        key: "createTime",
        width: "20%",
      },
      {
        title: "创建人",
        dataIndex: "creatorName",
        key: "creatorName",
        width: "16%",
        hiddenTooltip: true,
      },
      {
        title: "操作",
        dataIndex: "opration",
        render: (text, record) => {
          const edit = this.getOprateDisable("edit");
          const del = this.getOprateDisable("delete");
          const publish = this.getOprateDisable("publish");
          const stop = this.getOprateDisable("stop");
          const preview = this.getOprateDisable("preview");
          const copy = this.getOprateDisable("copy");
          return (
            <div>
              {copy && (
                <React.Fragment>
                  <a
                    onClick={(e) => {
                      e.preventDefault();
                      this.handleCreateVisible(true, record);
                    }}
                  >
                    复制
                  </a>
                  <Divider type="vertical" />
                </React.Fragment>
              )}
              {record.status === 0 ? (publish && (
                <React.Fragment>
                  <Popconfirm
                    placement="left"
                    title={`确定部署表单：${record.formName}?`}
                    onConfirm={() => {
                      this.handleOperate(record, 'publishForm');
                    }}
                    okText="确定"
                    cancelText="取消"
                  >
                    <a
                      onClick={(e) => {
                        e.preventDefault();
                      }}
                    >
                      部署
                    </a>
                  </Popconfirm>
                  <Divider type="vertical" />
                </React.Fragment>
              )) : (
                stop && record.status === 1 && (
                <React.Fragment>
                  <Popconfirm
                    placement="left"
                    title={`确定停用表单：${record.formName}?`}
                    onConfirm={() => {
                      this.handleOperate(record, 'stopForm');
                    }}
                    okText="确定"
                    cancelText="取消"
                  >
                    <a
                      onClick={(e) => {
                        e.preventDefault();
                      }}
                    >
                      停用
                    </a>
                  </Popconfirm>
                  <Divider type="vertical" />
                </React.Fragment>
              )
              )}
              {preview && (
                <React.Fragment>
                  <a
                    onClick={(e) => {
                      e.preventDefault();
                      this.previewForm(record);
                    }}
                  >
                    表单预览
                  </a>
                  <Divider type="vertical" />
                </React.Fragment>
              )}
              {edit && (
                <React.Fragment>
                  <Link
                    to={{
                      pathname: "/flowmanage/formbuilder",
                      search: queryString.stringify({
                        formId: record.formId,
                      }),
                    }}
                  >
                    修改
                  </Link>
                  <Divider type="vertical" />
                </React.Fragment>
              )}
              {del && (
                <React.Fragment>
                  <Popconfirm
                    placement="left"
                    title={`确定删除表单：${record.formName}?`}
                    onConfirm={() => {
                      this.handleOperate(record, 'delForm');
                    }}
                    okText="确定"
                    cancelText="取消"
                  >
                    <a
                      onClick={(e) => {
                        e.preventDefault();
                      }}
                    >
                      删除
                    </a>
                  </Popconfirm>
                </React.Fragment>
              )}
            </div>
          );
        },
      },
    ];
  }

  componentDidMount() {
    const { dispatch } = this.props;
    this.isLeaf = false;
    setTimeout(() => {
      this.initData();
      dispatch({ type: "appListMenu/getAppListData" });
    }, 300);
  }

  // componentDidUpdate(preProps) {
  //   const { focusApp } = this.props;
  //   const { focusApp: preFocusApp } = preProps;
  //   if (preFocusApp.id && `${preFocusApp.id || 0}` !== `${focusApp.id || 0}`) {
  //     // 应用切换更新页面数据
  //     this.resetPageData();
  //   }
  // }

  componentWillUnmount() {
    this.isLeaf = true;
    const { dispatch } = this.props;
    dispatch({ type: "FormConfigure/clearData" });
  }

  // 重置页面数据
  resetPageData = () => {
    const { dispatch } = this.props;
    this.queryParams = this.baseQueryParam;
    dispatch({ type: "FormConfigure/clearData" });
    this.setState({ page: { pageNum: 1, pageSize: 6 }, filterVisible: false });
    if (this.QueryExtra) this.QueryExtra.handleReset();
    if (this.AdvancedFilter) this.AdvancedFilter.handleReset();
  };

  getOprateDisable = (type) => {
    const {
      location: { pathname = "" },
      menuDataList,
      resourceList,
    } = this.props;
    const res = this.getPageOperate(type, pathname, menuDataList, resourceList);
    return res;
  };

  // 获取查询条件组件的this
  getRef = (type, _this) => {
    this[type] = _this;
  };

  // 获取查询参数
  getQueryParam = () => {
    const {
      page: { pageNum, pageSize },
    } = this.state;
    const {
      tenantId, appId, busiId,
    } = this;
    return { ...this.queryParams, pageNum, pageSize, tenantId,appId, busiId };
  };

  // 查询条件改变
  handleParamsChange = (item = {}) => {
    this.queryParams = { ...this.queryParams, ...item };
  };

  setSelectId = (tenantId, appId, busiId) => {
    this.tenantId = tenantId;
    this.appId = appId;
    this.busiId = busiId;
  }

  handleTypeSelect = (selectedKeys = [], e, _, normalSelectedKeys) => {
    const { page } = this.state;
    let [selectedKey] = selectedKeys;
    let normalSelectedKey = selectedKey;
    if (e.node.props.isLeaf) {
      [normalSelectedKey] = normalSelectedKeys;
    } else {
      // eslint-disable-next-line
      selectedKey = selectedKey.split('|')[1];
    }
    const keys = new Array(3).fill(undefined); 
    const newSelectedKeys = [];
    if (normalSelectedKey.indexOf('tenant') === 0) {
      // 重复点击清空选择
      if (this.tenantId !== selectedKey) {
        keys[0] = selectedKey;
        newSelectedKeys.push(normalSelectedKey);
      }
    } else if (normalSelectedKey.indexOf('app') === 0) {
      // 重复点击清空选择
      if (this.appId !== selectedKey) {
        keys[1] = selectedKey;
        newSelectedKeys.push(normalSelectedKey);
      }
    } else if (normalSelectedKey.indexOf('business') === 0) {
      // 重复点击清空选择
      if (this.busiId !== selectedKey) {
        keys[2] = selectedKey;
        newSelectedKeys.push(normalSelectedKey);
      }
    }
    this.setSelectId(...keys);
    this.setState({
      selectedKeys: newSelectedKeys,
      page: {
        ...page,
        pageNum: 1,
      },
    }, this.initData);
  }

  // 触发查询
  initData = () => {
    const { dispatch } = this.props;
    const params = this.getQueryParam();
    dispatch({ type: "FormConfigure/getListData", payload: params });
    // dispatch({ type: "appListMenu/getTenantList" });
  };

  // 页码页数改变
  handlePageChange = (pageNum, pageSize) => {
    this.setState({ page: { pageNum, pageSize } }, () => {
      this.initData();
    });
  };

  // 搜索
  handleSearch = () => {
    const { page } = this.state;
    this.setState({ page: { ...page, pageNum: 1 } }, () => {
      this.initData();
    });
  };

  // 创建流程弹窗
  handleCreateVisible = (visible, record) => {
    this.record = record;
    if (this.isLeaf) return;
    this.setState({ visible });
  };

  // 删除,部署，停用
  handleOperate = (record = {}, action) => {
    const { dispatch } = this.props;
    const { formId } = record;
    const map = {
      delForm: '删除',
      publishForm: '部署',
      stopForm: '停用',
    };
    if (!formId) return;
    dispatch({ type: `FormConfigure/${action}`, payload: { formId } }).then(
      ({ errCode, errMsg }) => {
        if (errCode === 0) {
          this.openNotificationWithIcon("success", "", `${map[action]}成功`);
          this.handleSearch();
        } else {
          this.openNotificationWithIcon("error", "", errMsg || `${map[action]}失败`);
        }
      },
    );
  };

  handleFilterVisible = () => {
    const { filterVisible } = this.state;
    this.setState({ filterVisible: !filterVisible });
  };

  // 预览
  previewForm = (record) => {
    const { dispatch } = this.props;
    const { formId, formName } = record || {};
    this.formTitle = formName;

    dispatch({ type: "FormConfigure/getFormDetail", payload: { formId } })
      .then(({ errCode, errMsg, datas }) => {
        const { fields = {} } = datas;
        if (errCode !== 0) {
          this.openNotificationWithIcon(
            "warning",
            "",
            errMsg || "获取表单详细信息失败",
          );
          return;
        }
        // const newFileds = detailFormat(fields || []);
        this.setState({ viewDatas: fields });
      })
      .finally(() => {
        this.customFormVisible(true);
      });
  };

  customFormVisible = (status) => {
    this.setState({ formVisible: status });
  };

  render() {
    const { formConfigStore, loading, dispatch, /* tenantList, */appListMenuData } = this.props;
    const {
      page: { pageNum, pageSize },
      visible,
      filterVisible,
      formVisible,
      viewDatas,
      selectedKeys,
    } = this.state;
    const { listData = [], totalCount = 0 } = formConfigStore;
    const listLoading = loading.effects["FormConfigure/getListData"];
    const createLoading = loading.effects["FormConfigure/addOrCopyForm"];
    const deleteLoading = loading.effects["FormConfigure/delForm"] || false;
    const publishLoading = loading.effects["FormConfigure/publishForm"] || false;
    const stopLoading = loading.effects["FormConfigure/stopForm"] || false;
    const detailLoading =
      loading.effects["FormConfigure/getFormDetail"] ||
      loading.effects["FormSelectModel/preRequestOuterData"] ||
      false;
    return (
      <div className={styles.root}>
        <PageLayout
          leftContent={
            <Card
              title="应用目录"
              style={{ width: "100%", height: "100%" }}
              extra={
                this.getOprateDisable("add") ? (
                  <a href="#" onClick={this.addAppBusiness}>
                    + 新建
                  </a>
                ) : null
              }
              bodyStyle={{
                minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104,
              }}
            >
              <Catalogue
                CatalogueData={appListMenuData}
                treeNodeSelect={this.handleTypeSelect}
                selectedKeys={selectedKeys}
              />
            </Card>
          }
          rightContent={
            <Spin spinning={deleteLoading || publishLoading || stopLoading} delay={300}>
              <Card
                title={
                  <CardTitle
                    total={totalCount}
                    handleCreateVisible={this.handleCreateVisible}
                    addVisible={this.getOprateDisable("add")}
                  />
                }
                extra={
                  <QueryExtra
                    onChange={this.handleParamsChange}
                    onSearch={this.handleSearch}
                    visible={filterVisible}
                    handleFilterVisible={this.handleFilterVisible}
                    getRef={(_this) => this.getRef("QueryExtra", _this)}
                    // tenantList={tenantList}
                    tenantList={appListMenuData}
                  />
                }
                bodyStyle={{
                  minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104,
                }}
                style={{ width: "100%" }}
              >
                <AdvancedFilter
                  handleSearch={this.handleSearch}
                  handleParamsChange={this.handleParamsChange}
                  visible={filterVisible}
                  getRef={(_this) => this.getRef("AdvancedFilter", _this)}
                />
                <TableList
                  dataSource={listData}
                  loading={listLoading}
                  columns={this.columns}
                  titleName="formName"
                  operationName="opration"
                  onPageChange={this.handlePageChange}
                  rowKey="formId"
                  className={styles.listcon}
                  pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                    pageSizeOptions: ["6", "10", "20", "30"],
                    current: pageNum,
                    pageSize,
                    total: totalCount,
                  }}
                />
              </Card>
            </Spin>
          }
        />
        <CreateForm
          visible={visible}
          handleCreateVisible={this.handleCreateVisible}
          dispatch={dispatch}
          confirmLoading={createLoading}
          data={this.record}
          // tenantList={tenantList}
          tenantList={appListMenuData}
        />
        {formVisible && (
          <CustomForm
            title={this.formTitle}
            visible={formVisible}
            confirmLoading={false}
            onOk={() => {
              this.customFormVisible(false);
            }}
            onCancel={() => {
              this.customFormVisible(false);
            }}
            formConfigData={viewDatas}
            dataLoading={detailLoading}
            dispatch={dispatch}
            isView
            // showMobile
          />
        )}
      </div>
    );
  }
}

export default FormConfigure;
